package com.xfcycle.zebrabikegp.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.constant.BluetoothDeviceConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.util.EncryptStringUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import java.math.BigInteger;

/**
 * 蓝牙钥匙设置
 */
public class BsBlueToothKeyActivity extends RootActivity {
    private static final String TAG = "BsBlueToothKeyActivity";

    private ImageView iv_bluetooth_key_back;

//    private EditText et_bluetooth_key_id;

    private Button btn_add_bluetooth_key;
    private Button btn_remove_bluetooth_key;
    private Button btn_clean_bluetooth_key;
    private Button btn_bluetooth_key_amount;

    private RelativeLayout rl_cover;
    private LinearLayout ll_my_key_amount;
    private TextView tv_my_key_amount;

    private HandleDataByBLEUtil handleDataByBLEUtil;
    private HandleDataBySharePreferencesUtil handleDataBySharePreferencesUtil;

    private BluetoothKeyHandleDataFromBleReceiver bluetoothKeyHandleDataFromBleReceiver;

    private boolean isAddBluetoothKey;

    private boolean isBindKey = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bs_bluetooth_key);

        initView();
        initViewListener();
        setViewContent();
    }

    @Override
    protected void onResume() {
        super.onResume();

        //注册广播
        bluetoothKeyHandleDataFromBleReceiver = new BluetoothKeyHandleDataFromBleReceiver();
        registBroadcastReceiverAtActivity(bluetoothKeyHandleDataFromBleReceiver, BluetoothDeviceConstant.GET_DATA_FROM_BLUETOOTH_BROADCAST_RECEIVER_ACTION);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //回收广播接收者
        unregisterReceiver(bluetoothKeyHandleDataFromBleReceiver);
    }
    /***********************************************************************************************/
    /**                                 初始化控件对象 监听 控件内容方法                             **/
    /***********************************************************************************************/

    private void initView() {
        iv_bluetooth_key_back = (ImageView) findViewById(R.id.iv_bluetooth_key_back);
        rl_cover = (RelativeLayout) findViewById(R.id.rl_cover);
        ll_my_key_amount = (LinearLayout) findViewById(R.id.ll_my_key_amount);
        tv_my_key_amount = (TextView) findViewById(R.id.tv_my_key_amount);

        btn_add_bluetooth_key = (Button) findViewById(R.id.btn_add_bluetooth_key);
        btn_remove_bluetooth_key = (Button) findViewById(R.id.btn_remove_bluetooth_key);
        btn_clean_bluetooth_key = (Button) findViewById(R.id.btn_clean_bluetooth_key);
        btn_bluetooth_key_amount = (Button) findViewById(R.id.btn_bluetooth_key_amount);

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, -1);
        handleDataBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);
    }

    private void initViewListener() {
        //回退事件监听
        iv_bluetooth_key_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //添加蓝牙遥控
        btn_add_bluetooth_key.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAddBluetoothKey = true;
                startActivityForResult(new Intent(BsBlueToothKeyActivity.this, CaptureActivity.class), REQUEST_CODE_FIND_BIKE_QRCODE);
            }
        });

        //移除蓝牙遥控
        btn_remove_bluetooth_key.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAddBluetoothKey = false;
                startActivityForResult(new Intent(BsBlueToothKeyActivity.this, CaptureActivity.class), REQUEST_CODE_FIND_BIKE_QRCODE);
            }
        });

        //清空蓝牙钥匙
        btn_clean_bluetooth_key.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleDataByBLEUtil.sendDataToDevice("s|5,r");
            }
        });

        //查询当前绑定蓝牙钥匙数量
        btn_bluetooth_key_amount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断车辆是否解锁
                if (!BlueToothAssist.isConnect) {
                    Toast.makeText(BsBlueToothKeyActivity.this.getApplicationContext(), ToastConstant.BIKE_LOCKED, Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!BlueToothAssist.isUnlock) {
                    Toast.makeText(BsBlueToothKeyActivity.this.getApplicationContext(), ToastConstant.BIKE_LOCKED, Toast.LENGTH_SHORT).show();
                    return;
                }

                if (null != rl_cover) {
                    rl_cover.setVisibility(View.VISIBLE);
                }

                //查询蓝牙钥匙绑定数量
                handleDataByBLEUtil.sendDataToDevice("s|5,g");

                isBindKey = false;

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SystemClock.sleep(5 * 1000);

                        //没有等待时间到 没有接受到回馈
                        if (!isBindKey) {
                            refreshKeyAmount("0");
                        }
                    }
                }).start();
            }
        });
    }

    private void setViewContent() {
    }

    /**
     * 更新绑定蓝牙钥匙数量
     */
    private void refreshKeyAmount(final String bindKeyAmount) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    ll_my_key_amount.setVisibility(View.VISIBLE);
                    tv_my_key_amount.setText(bindKeyAmount);

                    if (null != rl_cover) {
                        rl_cover.setVisibility(View.GONE);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /***********************************************************************************************/
    /**                             处理从不同途径获得的数据                                         **/
    /***********************************************************************************************/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                //获得 扫描二维码 得到蓝牙钥匙名称
                case REQUEST_CODE_FIND_BIKE_QRCODE:
                    Bundle qrCodeBundle = data.getExtras();
                    if (null == qrCodeBundle || null == qrCodeBundle.getString("result")) {
                        Log.e(TAG, "onActivityResult: 蓝牙钥匙名称未取到");
                        return;
                    }

                    //获取蓝牙钥匙id
                    String bluetoothKeyId = getBluetoothKeyId(qrCodeBundle.getString("result").replace("\n", "").replace("\r", ""));

                    //判断是添加蓝牙钥匙还是移除蓝牙钥匙
                    if (isAddBluetoothKey) {
                        Log.w(TAG, "onActivityResult: -------------------- 添加蓝牙钥匙：" + bluetoothKeyId);
                        handleDataByBLEUtil.sendDataToDevice("s|5,a," + bluetoothKeyId);
                    } else {
                        Log.w(TAG, "onActivityResult: -------------------- 移除蓝牙钥匙：" + bluetoothKeyId);
                        handleDataByBLEUtil.sendDataToDevice("s|5,d," + bluetoothKeyId);
                    }

                    break;
            }
        }
    }

    private String getBluetoothKeyId(String code) {
        String[] params = code.split(" ");
        if (params.length < 3) {
            return null;
        }

        Integer index = Integer.parseInt(params[1]);
        String key = EncryptStringUtil.getMd5(BluetoothDeviceConstant.AUTH_KEY_TAB[index].toUpperCase() + " " + params[2] + " " + "X4cycleX4cycleX4cycleX4cycleX4cycle").substring(0, 16).toUpperCase();
        String value = params[0];

        BigInteger bigInteger1 = new BigInteger(value, 16);
        BigInteger bigInteger2 = new BigInteger(key, 16);

        String str1 = bigInteger1.xor(bigInteger2).toString(16);

        StringBuilder sbId = new StringBuilder();
        for (int i = 0; i < str1.length(); i = i + 2) {
            String s = str1.substring(i, i + 2);
            byte byte1 = (byte) Integer.parseInt(s, 16);
            sbId.append((char) byte1);
        }
        return sbId.toString();
    }
    /***********************************************************************************************/
    /**                                 自定义广播接收者类                                          **/
    /***********************************************************************************************/

    /**
     * 广播接收者类，负责接收从蓝牙发出的数据并对其进行处理
     */
    class BluetoothKeyHandleDataFromBleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("result");

            //添加蓝牙钥匙成功
            if (result.contains("s|5,a")) {
                Toast.makeText(context.getApplicationContext(), ToastConstant.ADD_BLE_KEY_SUCCESS, Toast.LENGTH_SHORT).show();

                //判断之前已经查过车辆绑定蓝牙钥匙数量
                if(View.VISIBLE == ll_my_key_amount.getVisibility()){
                    //查询蓝牙钥匙绑定数量
                    handleDataByBLEUtil.sendDataToDevice("s|5,g");
                }

                return;
            }

            //删除蓝牙钥匙成功
            if (result.contains("s|5,d")) {
                Toast.makeText(context.getApplicationContext(), ToastConstant.DELETE_BLE_KEY_SUCCESS, Toast.LENGTH_SHORT).show();

                if(View.VISIBLE == ll_my_key_amount.getVisibility()){
                    handleDataByBLEUtil.sendDataToDevice("s|5,g");
                }

                return;
            }

            //清空蓝牙钥匙成功
            if (result.contains("s|5,r")) {
                Toast.makeText(context.getApplicationContext(), ToastConstant.CLEAN_BLE_KEY_SUCCESS, Toast.LENGTH_SHORT).show();
                return;
            }

            //获取蓝牙钥匙数量 ^s|5,g,n,2$
            if (result.contains("s|5,g,n")) {
                isBindKey = true;
                String bindKeyAmount = result.replace("^s|5,g,n,", "").replace("$", "");
                refreshKeyAmount(bindKeyAmount);
                return;
            }

            //获取蓝牙钥匙具体信息
            if (result.contains("s|5,g")) {
                return;
            }

            //修改蓝牙钥匙失败
            Toast.makeText(context.getApplicationContext(), ToastConstant.MODIFY_BLE_KEY_FAILURE, Toast.LENGTH_SHORT).show();
        }
    }
}
